<!doctype html>
<html>
	<head>
		<meta charset="utf-8">
		<title>Cursor Bind</title>
		<meta name="viewport" content="width=device-width, initial-scale=1">

		<link rel="stylesheet" href="../dist/uPlot.min.css">
		<style>
			.u-annotate {
				background: rgba(255,255,0,0.3);
			}
		</style>
	</head>
	<body>
		<script src="../dist/uPlot.iife.js"></script>
		<script>
			let xs = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30];
			let vals = [-10,-9,-8,-7,-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6,7,8,9,10];

			let data = [
				xs,
				xs.map((t, i) => vals[Math.floor(Math.random() * vals.length)]),
				xs.map((t, i) => vals[Math.floor(Math.random() * vals.length)]),
				xs.map((t, i) => vals[Math.floor(Math.random() * vals.length)]),
			];

			let annotating = false;

			const opts = {
				width: 1920,
				height: 600,
				title: "Cursor Bind (try Ctrl + drag)",
				cursor: {
					bind: {
						mousedown: (u, targ, handler) => {
							return e => {
								if (e.button == 0) {
									handler(e);

									if (e.ctrlKey) {
										annotating = true;

										// switch select region to annotation color
										u.root.querySelector(".u-select").classList.add("u-annotate");
									}
								}
							}
						},
						mouseup: (self, targ, handler) => {
							return e => {
								if (e.button == 0) {
									if (annotating) {
										// tmp disable drag.setScale
										const _setScale = u.cursor.drag.setScale;
										u.cursor.drag.setScale = false;

										// fire original handler
										handler(e);

										// revert drag.setScale
										u.cursor.drag.setScale = _setScale;
									}
									else
										handler(e);
								}
							};
						}
					},
				},
				hooks: {
					init: [
						u => {
							// should only fire when not dragging
							u.over.addEventListener('click', e => {
								console.log('click!');
							});
						}
					],
					setSelect: [
						u => {
							if (annotating) {
								let note = prompt("Annotation Text");

								// revert select region to default color
							//	u.root.querySelector(".u-select").classList.remove("u-annotate");

								annotating = false;
							}
						}
					]
				},
				scales: {
					x: {
						time: false,
					},
				},
				series: [
					{},
					{
						stroke: "red",
						fill: "rgba(255,0,0,0.1)",
					},
					{
						stroke: "green",
						fill: "rgba(0,255,0,0.1)",
					},
					{
						stroke: "blue",
						fill: "rgba(0,0,255,0.1)",
					},
				],
			};

			let u = new uPlot(opts, data, document.body);
		</script>
	</body>
</html>